package com.weipeep.sys.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.weipeep.common.base.BaseController;
import com.weipeep.common.mail.EmailService;
import com.weipeep.common.utils.DateUtils;
import com.weipeep.common.utils.MD5Utils;
import com.weipeep.common.utils.Result;
import com.weipeep.sys.dao.ProductDao;
import com.weipeep.sys.domain.*;
import com.weipeep.sys.service.*;
import com.weipeep.sys.vo.DemandVo;
import com.weipeep.sys.vo.ProductResponse;
import com.weipeep.sys.vo.ProductSearch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

@Controller
public class FrontController extends BaseController{
    @Resource
    private DemandService demandService;
    @Resource
    private ProductService productService;
    @Resource
    private BaoJiaService baoJiaService;
    @Resource
    private WebUserService webUserService;
    @Autowired
    private PasswordService passwordService;
    @Resource
    private EmailService emailService;
    @Resource
    private NewsService newsService;

    @GetMapping("/front/news/{id}")
    public String news(@PathVariable("id") Long id,Model model){
        model.addAttribute("news",newsService.selectById(id));
        UserBase webUserDO = getUser();
        if(webUserDO!=null){
            model.addAttribute("user",webUserDO);
            model.addAttribute("isLogin",true);
        }else {
            model.addAttribute("isLogin",false);
        }
        return "news";
    }
    @GetMapping("/front/newsdetail/{id}")
    public String newsdetail(@PathVariable("id") Long id,Model model){
        model.addAttribute("news",newsService.selectById(id));
        return "newsdetail";
    }
    @GetMapping("/front/abd")
    public String abd(ProductSearch productSearch,Model model){
        UserBase webUserDO = getUser();
        if(webUserDO!=null){
            model.addAttribute("user",webUserDO);
            model.addAttribute("isLogin",true);
        }else {
            model.addAttribute("isLogin",false);
        }
        model.addAttribute("productSearch",productSearch);
        return "abd";
    }
    @GetMapping("/front/findpassword")
    public String findpassword(ProductSearch productSearch,Model model){
        UserBase webUserDO = getUser();
        if(webUserDO!=null){
            model.addAttribute("user",webUserDO);
            model.addAttribute("isLogin",true);
        }else {
            model.addAttribute("isLogin",false);
        }
        model.addAttribute("productSearch",productSearch);
        return "findpassword";
    }
    @GetMapping("/front/resetpassword")
    public String resetpassword(String sid,ProductSearch productSearch,Model model){
        UserBase webUserDO = getUser();
        if(webUserDO!=null){
            model.addAttribute("user",webUserDO);
            model.addAttribute("isLogin",true);
        }else {
            model.addAttribute("isLogin",false);
        }
        model.addAttribute("productSearch",productSearch);
        model.addAttribute("sid",sid);
        return "resetpassword";
    }
    @ResponseBody
    @GetMapping("/front/demand/search")
    public Result<Page<DemandVo>> search(Integer pageNumber, Integer pageSize, DemandVo demandDTO){
        // 查询列表数据
        Page<DemandDO> page = new Page<>(pageNumber, pageSize);
        Page<DemandVo> pageDemandVo = new Page<>(pageNumber, pageSize);
        Wrapper<DemandDO> wrapper = new EntityWrapper<DemandDO>();
        if (demandDTO.getModel()!=null&&demandDTO.getModel().trim().length()>0){
            wrapper.like("model",demandDTO.getModel());
        }
        wrapper.orderBy("create_time desc");
        page = demandService.selectPage(page, wrapper);
        BaoJiaDO baoJiaDO = new BaoJiaDO();
        baoJiaDO.setUserId(getUserId());
        Wrapper<BaoJiaDO> wrapperBaoJiaDO = new EntityWrapper<BaoJiaDO>(baoJiaDO);
        wrapperBaoJiaDO.addFilter("demand_id is not null");
        List<BaoJiaDO> baoJiaDOList = baoJiaService.selectList(wrapperBaoJiaDO);
        Set<Long> yibaojias = Sets.newHashSet();
        baoJiaDOList.stream().forEach(baoJiaDO1 ->{
            yibaojias.add(baoJiaDO1.getDemandId());
        });
        Set<Long> userIds = Sets.newConcurrentHashSet();
        Page<DemandVo> pageresult = new Page<>(pageNumber, pageSize);
        page.getRecords().forEach(xunJiaDO -> userIds.add(xunJiaDO.getUserId()));
        Map<Long, WebUserDO> map = Maps.newHashMap();
        if (userIds.size()>0) {
            List<DemandVo> resultList = Lists.newArrayList();
            List<WebUserDO> webUserDOList = webUserService.selectBatchIds(Lists.newArrayList(userIds));
            for (WebUserDO webUserDO : webUserDOList) {
                map.put(webUserDO.getId(), webUserDO);
            }
        }
        List<DemandVo> resultList = Lists.newArrayList();
        if (page.getRecords()!=null && page.getRecords().size()>0){
            page.getRecords().forEach(demandDO -> {
                DemandVo demandVo = new DemandVo();
                demandVo.setBrand(demandDO.getBrand());
                demandVo.setUserId(demandDO.getUserId());
                demandVo.setCreateTime(demandDO.getCreateTime());
                demandVo.setId(demandDO.getId());
                demandVo.setModel(demandDO.getModel());
                demandVo.setNote(demandDO.getNote());
                demandVo.setNumber(demandDO.getNumber());
                demandVo.setReceivePrice(demandDO.getReceivePrice());
                demandVo.setType(demandDO.getType());
                if (map.get(demandDO.getUserId())!=null){
                    demandVo.setCompany(map.get(demandDO.getUserId()).getCompany());
                    demandVo.setUserAccount(map.get(demandDO.getUserId()).getUserAccount());
                    demandVo.setMobile(map.get(demandDO.getUserId()).getMobile());
                    demandVo.setQq(map.get(demandDO.getUserId()).getQq());
                    demandVo.setTelephone(map.get(demandDO.getUserId()).getTelephone());
                }
                if (yibaojias.contains(demandDO.getId())){
                    demandVo.setHasBaojia(true);
                }else {
                    demandVo.setHasBaojia(false);
                }
                resultList.add(demandVo);
            });
        }
        pageDemandVo.setRecords(resultList);
        int total = demandService.selectCount(wrapper);
        pageDemandVo.setTotal(total);
        return Result.ok(pageDemandVo);
    }

    @GetMapping("/front/product/tosearch")
    public String productToSearch(ProductSearch productSearch, Model model){
        UserBase webUserDO = getUser();
        if(webUserDO!=null){
            model.addAttribute("user",webUserDO);
            model.addAttribute("isLogin",true);
        }else {
            model.addAttribute("isLogin",false);
        }
        model.addAttribute("productSearch",productSearch);

        // 查询列表数据
        return "abd";
    }

    @ResponseBody
    @GetMapping("/front/product/search")
    public Result<Page<ProductResponse>> productSearch(Integer pageNumber, Integer pageSize, ProductSearch productSearch){
        // 查询列表数据
        Page<ProductResponse> page = new Page<>(pageNumber, pageSize);
        productSearch.setOffset(page.getOffset());
        productSearch.setLimit(page.getLimit());
        if (productSearch.getBrand()!=null && productSearch.getBrand().trim().length()>0){
            productSearch.setBrand("%"+productSearch.getBrand()+"%");
        }
        if (productSearch.getModel()!=null && productSearch.getModel().trim().length()>0){
            productSearch.setModel("%"+productSearch.getModel()+"%");
        }
        if (productSearch.getType()!=null && productSearch.getType().trim().length()>0){
            productSearch.setType("%"+productSearch.getType()+"%");
        }
        page = productService.selectProductPage(page, productSearch);
        int total = productService.selectProductCount(productSearch);
        page.setTotal(total);
        return Result.ok(page);
    }
    @ResponseBody
    @PostMapping("/front/sentEmail")
    public Result sentEmail(String email){
        Map<String,Object> map = Maps.newHashMap();
        map.put("email",email);
        List<WebUserDO> webUserDOList = webUserService.selectByMap(map);
        if (webUserDOList.size()>0){
            WebUserDO webUserDO = webUserDOList.get(0);
            Map<String,Object> m = Maps.newHashMap();
            m.put("user_id",webUserDO.getId());
            passwordService.deleteByMap(m);
            PasswordDO passwordDO = new PasswordDO();
            passwordDO.setOverTime(new Date(Calendar.getInstance().getTime().getTime()+1800000l));
            passwordDO.setSid(UUID.randomUUID().toString());
            passwordDO.setUserId(webUserDO.getId());
            passwordDO.setValid(1);
            passwordService.insert(passwordDO);
            String url="http://www.01bearing.com/front/resetpassword?sid="+passwordDO.getSid();
            final String subject = "密码重置";
            final StringBuilder sb = new StringBuilder();
            sb.append("<html>");
            sb.append("<body>");
            sb.append("<div>尊敬的会员您好，您的登陆账户为："+webUserDO.getUserAccount()+"</div>");
            sb.append("<div>请点击以下链接进行密码重置：</div>");
            sb.append("<div><a href='"+url+"'>点我重置密码</a></div>");
            sb.append("</body>");
            sb.append("</html>");
            new Thread(){
                @Override
                public void run() {
                        emailService.sendHtmlMail(email,subject,sb.toString());
                }
            }.start();
            log.info(url);
        }else {
            return Result.fail().setMsg("邮箱不存在");
        }
        return Result.ok();
    }
    @ResponseBody
    @PostMapping("/front/resetPassword")
    public Result resetPassword(String sid,String password){
        Map<String,Object> map = Maps.newHashMap();
        map.put("sid",sid);
        List<PasswordDO> passwordDOList= passwordService.selectByMap(map);
        if (passwordDOList.size()>0){
            PasswordDO passwordDO = passwordDOList.get(0);
            if (passwordDO.getValid()==1){
                if (passwordDO.getOverTime().getTime()>Calendar.getInstance().getTime().getTime()){
                    WebUserDO webUserDO = webUserService.selectById(passwordDO.getUserId());
                    password = MD5Utils.encrypt(webUserDO.getUserAccount(), password);
                    webUserDO.setPassword(password);
                    webUserService.updateById(webUserDO);
                    passwordDO.setValid(0);
                    passwordService.updateById(passwordDO);
                }else {
                    return Result.fail().setMsg("重置密码已失效，请重新发送重置邮件");
                }
            }else {
                return Result.fail().setMsg("重置密码已失效，请重新发送重置邮件");
            }
        }else {
            return Result.fail().setMsg("无效重置");
        }
        return Result.ok();
    }
    @GetMapping("/front/about")
    public String about(Model model){
        // 查询列表数据
        UserBase webUserDO = getUser();
        if(webUserDO!=null){
            model.addAttribute("user",webUserDO);
            model.addAttribute("isLogin",true);
        }else {
            model.addAttribute("isLogin",false);
        }
        return "foot/about";
    }
    @GetMapping("/front/contact")
    public String contact(Model model){
        // 查询列表数据
        UserBase webUserDO = getUser();
        if(webUserDO!=null){
            model.addAttribute("user",webUserDO);
            model.addAttribute("isLogin",true);
        }else {
            model.addAttribute("isLogin",false);
        }
        return "foot/contact";
    }
    @GetMapping("/front/complain")
    public String complain(Model model){
        // 查询列表数据
        UserBase webUserDO = getUser();
        if(webUserDO!=null){
            model.addAttribute("user",webUserDO);
            model.addAttribute("isLogin",true);
        }else {
            model.addAttribute("isLogin",false);
        }
        return "foot/complain";
    }
    @GetMapping("/front/law")
    public String law(Model model){
        // 查询列表数据
        UserBase webUserDO = getUser();
        if(webUserDO!=null){
            model.addAttribute("user",webUserDO);
            model.addAttribute("isLogin",true);
        }else {
            model.addAttribute("isLogin",false);
        }
        return "foot/law";
    }
    @GetMapping("/front/payment")
    public String payment(Model model){
        // 查询列表数据
        UserBase webUserDO = getUser();
        if(webUserDO!=null){
            model.addAttribute("user",webUserDO);
            model.addAttribute("isLogin",true);
        }else {
            model.addAttribute("isLogin",false);
        }
        return "foot/payment";
    }
    @GetMapping("/front/supervision")
    public String supervision(Model model){
        // 查询列表数据
        UserBase webUserDO = getUser();
        if(webUserDO!=null){
            model.addAttribute("user",webUserDO);
            model.addAttribute("isLogin",true);
        }else {
            model.addAttribute("isLogin",false);
        }
        return "foot/supervision";
    }
    @GetMapping("/front/disclaimer")
    public String disclaimer(Model model){
        // 查询列表数据
        UserBase webUserDO = getUser();
        if(webUserDO!=null){
            model.addAttribute("user",webUserDO);
            model.addAttribute("isLogin",true);
        }else {
            model.addAttribute("isLogin",false);
        }
        return "foot/disclaimer";
    }
    @RequestMapping("/front/checkLogin")
    @ResponseBody
    public Result<String> checkLogin(){
        // 查询列表数据
        UserBase webUserDO = getUser();
        if(webUserDO!=null){
            return Result.ok();
        }else {
            return Result.fail().setMsg("未登录，不能进行询价");
        }
    }
}
